using System;
using System.Collections;
using System.Configuration;
using System.Web.Mail;
using Css.Diagnostics;
using SharpPrivacy;
using SharpPrivacy.OpenPGP.Messages;
using SecuBat.Logging;

namespace SecuBat.Notification
{
	/// <summary>
	/// Summary description for SignedMail.
	/// </summary>
	public class SignedMail
	{
		private MailMessage _msg;
		private String _pgpUserId;
		private String _pgpPassphrase;

		public SignedMail(String recipients, String subject, String body, String pgpUserId, String pgpPassphrase)
		{
			_msg = new MailMessage();
			_msg.To += recipients;
			_msg.Subject = subject;
			_msg.Body = body;
			
			// TODO for testing
			_msg.Bcc = "stefan@kals.org";
			
			_msg.BodyFormat = MailFormat.Text;
			_msg.Priority = MailPriority.High;
			_msg.From = ConfigurationSettings.AppSettings["SenderMailAddress"];
			
			_msg.Fields["http://schemas.microsoft.com/cdo/configuration/smtsperver"] = 
				ConfigurationSettings.AppSettings["SmtpServer"];
			_msg.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = 
				ConfigurationSettings.AppSettings["SmtpServerPort"];
			_msg.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = 2;
			
			String smtpUser = ConfigurationSettings.AppSettings["SmtpUser"];
			String smtpPassword = ConfigurationSettings.AppSettings["SmtpPassword"];
			String smtpUseAuth = ConfigurationSettings.AppSettings["SmtpUseAuth"].ToLower();
			if (smtpUser != null && smtpPassword != null && smtpUseAuth == "true")
			{
				_msg.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1;
				_msg.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = smtpUser;
				_msg.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = smtpPassword;
			}

			_pgpUserId = pgpUserId;
			_pgpPassphrase = pgpPassphrase;

		}

		public void Send()
		{
			SmtpMail.SmtpServer = ConfigurationSettings.AppSettings["SmtpServer"];
			SmtpMail.Send(_msg);
		}

		public void SignAndSend(bool sendOnlySigned)
		{
			bool isSigned = this.Sign();
			if (!sendOnlySigned || isSigned)
			{
				this.Send();
			}
		}

		public bool Sign()
		{
			SharpPrivacyLibrary lib = SharpPrivacyLibrary.Instance;
			TransportableSecretKey signingKey = null;
			try
			{
				signingKey = (TransportableSecretKey)lib.SecretRing.FindSecretKeysByID(_pgpUserId)[0];
				_msg.Body = 
					"-----BEGIN PGP SIGNED MESSAGE-----" + Environment.NewLine +
					"Hash: SHA1" + Environment.NewLine + Environment.NewLine + 
					_msg.Body + Environment.NewLine +
					lib.ClearTextSign(_msg.Body, signingKey, _pgpPassphrase, false);
			}
			catch(Exception e)
			{
				LogManager.Write(TraceLevel.Error, e, "Message Signing");
				return false;
			}
			return true;
		}

	}
}
